<?php

$db = db::getInstance();

//récuperation des donnees 
$valeurs = $_POST['contenu'];
$nom_formulaire = $_POST['form_name'];
$nbr_champ = $_POST['nb_champ'];
$nom_user = $_POST['login'];


$form_data = new DonneesModel();
$user_data = new UserDataModel();
$user_get = new UsersListModel();
$reference = new UserDataRefModel();

// récuperation du id du user considerer 
$filter1 = array(new DFC(UsersListModel::FIELD_LOGIN, $nom_user, DFC::EXACT));
$attributs_nom_user = UsersListModel::findByFilter($db, $filter1);

foreach ($attributs_nom_user as $attribut) {
    $id_user = $attribut->getIdUser();
}
// recuperation du id du formulaire concerner 
$filter2 = array(new DFC(DonneesModel::FIELD_FORM_NAME, $nom_formulaire, DFC::EXACT));
$attributs_nom_form = DonneesModel::findByFilter($db, $filter2);

foreach ($attributs_nom_form as $attribut) {
    $id_form = $attribut->getIdForm();
}

// tester si ce user a déja rempli le formulaire 
$filter3= array(new DFC(UserDataModel::FIELD_FORM_ID,$id_form, DFC::EXACT),
        (new DFC(UserDataModel::FIELD_USER_ID, $id_user, DFC::EXACT)));
$exist= UserDataModel::findByFilter($db, $filter3);

$il_exist="";
foreach ($exist as $x) {
    $il_exist = $x->getFormId();
}
echo $il_exist;
if  ($il_exist=="")
{

// table user_data
$user_data->setFormId($id_form);
$user_data->setUserId($id_user);
$user_data->setDate(date("d-m-Y") . '---' . date("H:i"));
$user_data->insertIntoDatabase($db);

$i = 0;

//table user_data_ref
while ($i <= $nbr_champ) {
    $reference->setIdRef($user_data->getIdRef());
    $reference->setKey($valeurs[$i]);
    $reference->setValue($valeurs[$i + 1]);
    
    $i = $i + 2;

    $reference->insertIntoDatabase($db);
}
echo "well done";
}
?>